const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session')
const MongoStore = require('connect-mongo')
const indexRouter = require('./routes/index');
const apiRouter = require('./routes/apis/lists');
const apiAuthRouter = require('./routes/apis/auth')
const authRouter = require('./routes/auth');

const {DBHOST,DBPORT,DBNAME} = require('./config/config')

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  name: 'sid', //设置cookie的name，默认值：connect.sid
  secret: 'mkbk', //盐值
  saveUninitialized: false, //为每次请求都设置一个cookie来存储session的id
  resave: true, //每次请求重新保存token(刷新过期时间)
  store: MongoStore.create({
    mongoUrl: `mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
  }),
  cookie: {
    httpOnly: true, //开启后前端无法操作该cookie
    maxAge: 1000 * 60 * 30 //过期时间
  }
}))

app.use('/', indexRouter);
app.use('/',authRouter)
app.use('/api', apiRouter);
app.use('/api', apiAuthRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.render('404')
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
